<template>
  <div>
    <!-- <van-button type="primary" @click="toWatchGoodsDetail()">打开商品页</van-button> -->
    <div id="wrap" class="chatroom"></div>
    <div class="plv-demo-product">
      <product-list
        :product-sdk="productSdk"
        :lang="lang"
        @browse-product="handleBrowseProduct"
        @click-buy="handleClickBuy"
      ></product-list>

      <div class="c-product-bubble">
        <product-bubble
          :product-sdk="productSdk"
          :lang="lang"
          :getLinkParams="getLinkParams"
          @click-buy="handleClickBuy"
        />
      </div>
    </div>
  </div>
</template>
<script>
import PolyvApi from '@/utils/api'
import { getVideoToken, getChatSign, getChatToken } from '@/api/goods/watch'
import { updateConfig, getApiToken } from '@polyv/interactions-receive-sdk'
import { Product } from '@polyv/interactions-receive-sdk'
import ProductList from '@polyv/interactions-receive-sdk-ui-default/lib/MobileProduct'
import ProductBubble from '@polyv/interactions-receive-sdk-ui-default/lib/ProductBubble'
import { ynToBool } from '@/utils'
export default {
  components: {
    ProductList,
    ProductBubble
  },
  props: {
    lang: {
      type: String,
      default: 'zh_CN'
    }
  },
  data() {
    return {
      // avatarTruenameList: {
      //   avatar: 'https://cdn.www.wangpaiyixue.cn/static/img/head0.317dbc9a.png',
      //   truename: '游客'
      // },
      // 保利威
      show: true,
      vodPlayerJs: 'https://player.polyv.net/script/player.js',
      playerJs: 'https://player.polyv.net/resp/live-h5-player/latest/liveplayer.min.js',
      playerList: {
        vid: null,
        playsafe: null,
        appId: null,
        ts: null,
        sign: null,
        uid: null,
        channel_id: null,
        sessionId: null
      },
      // 商品库 SDK 实例
      productSdk: null
    }
  },

  computed: {
    loginList() {
      return this.$store.getters.loginList
    },
    profileList() {
      return this.$store.getters.profileList
    }
  },

  mounted() { },
  created() {
    // this.$nextTick(() => {
    this.watch()
    // })
    this.productSdk = new Product()
    console.log(this.productSdk, 'prod')
    // this.productSdk.on(this.productSdk.events.PRODUCT_MESSAGE, msg => {
    //   const ProductMessageStatus = this.productSdk.ProductMessageStatus
    //   const status = `${msg.status}`
    //   if (status === ProductMessageStatus.ProductSwitch) {
    //     this.$emit('change-switch', ynToBool(msg.content.enabled))
    //   }
    // })
  },
  beforeDestroy() {
    this.productSdk?.destroy()
    this.productSdk = null
  },

  methods: {
    // 观看视频
    watch(row) {
      const data = {
        vid: null,
        goods_id: this.$route.query.goods_id,
        lesson_id: this.$route.query.lesson_id
      }
      getVideoToken(data).then(res => {
        this.playerList.channel_id = this.$route.query.channel_id
        // this.getPolyvLiveSdk()
        // this.loadPlayerScript1(this.loadPlayer1)
        this.getChatRoom()
      })
    },
    // 直播
    getPolyvLiveSdk() {
      const PolyvLiveSdk = window.PolyvLiveSdk
      let liveSdk
      getChatSign({ channel_id: this.playerList.channel_id }).then(res => {
        // console.log(res)
        this.playerList.appId = res.data.appId
        this.playerList.channelId = res.data.channelId
        this.playerList.timestamp = res.data.timestamp
        this.playerList.sign = res.data.sign
        liveSdk = new PolyvLiveSdk({
          channelId: res.data.channelId,
          sign: res.data.sign, // 频道验证签名
          timestamp: res.data.timestamp, // 毫秒级时间戳
          appId: res.data.appId, // polyv 后台的appId
          user: {
            userId: this.loginList.no,
            userName: this.profileList.truename,
            pic: this.profileList.avatar
          }
        })
        liveSdk.on(PolyvLiveSdk.EVENTS.CHANNEL_DATA_INIT, (event, data) => {
          // console.log(event, data, 'event, data')
          this.playerList.sessionId = data.sessionId
          liveSdk.setupPlayer({
            // setupPlayer：播放器配置对象
            pptEl: '#ppt',
            el: '#player',
            type: 'auto',
            controllerPosition: 'player',
            autoplay: true // 设置自动播放
          })
        })
      })

      // // 监听频道信息并初始化播放器
    },

    // 聊天室
    getChatRoom() {
      document.getElementById('wrap').innerHTML = ''
      // 获取聊天室ID
      const data = {
        no: this.loginList.no,
        channel_id: this.playerList.channel_id
      }
      getChatToken(data).then(response => {
        var chatroom = new PolyvChatRoom({
          roomId: response.data.roomId,
          userId: this.loginList.no,
          pic: this.profileList.avatar,
          nick: this.profileList.truename,
          token: response.data.token,
          mediaChannelKey: response.data.mediaChannelKey,
          version: '2.0',
          container: '#wrap',
          width: '100%',
          height: '100%',
          userType: 'slice',
          accountId: '',
          showUserList: false,
          showOwnInfo: true,
          enableAsk: false,
          tabData: [
            {
              name: `直播介绍`,
              type: 'intro'
            },
            {
              name: `互动聊天`,
              type: 'chat'
            },
            {
              name: `边看边买`,
              type: 'porduct'
            }
          ],
          customChatColor: {
            selfBgColor: '#2b2c35',
            selfColor: '#fff',
            otherBgColor: '#2b2c35',
            otherColor: '#fff',
            specialBgColor: '#2b2c35',
            specialColor: '#fff'
          },
          roomMessage: function (data) {
            // data为聊天室socket消息，当有聊天室消息时会触发此方法
            console.log(data)
          }
        })
        updateConfig({
          // 观众信息
          userInfo: {
            // 昵称
            nick: this.profileList.truename,
            // 头像
            pic: this.profileList.avatar,
            // 观众id
            userId: this.loginList.no
          },
          // 频道信息
          channelInfo: {
            // 频道号
            channelId: this.playerList.channel_id,
            // 房间号
            roomId: response.data.roomId,
            // 频道场次id
            sessionId: this.playerList.sessionId
          },
          // 此处传入 socketio 实例，具体获取方式请看下文
          socket: chatroom.chat.socket,
          // viewerApiToken 更新函数
          getViewerApiToken: callback => {
            this.myViewerApiTokenGetter(callback)
          }
        })
      })

      // 聊天室结束
    },
    // async getViewerApiToken() {
    //   var params = {
    //     appId: this.playerList.appId, // 账号appId
    //     channelId: this.playerList.channelId, // 频道号
    //     timestamp: this.playerList.timestamp, // 时间戳
    //     viewerId: this.loginList.no, // 观看者用户Id
    //     sign: this.playerList.sign
    //   }
    //   console.log(params, 'paramsparamsparams')
    //   const viewerApiToken = '137fa0b43f'
    //   console.log(viewerApiToken, '123123132')
    //   // 回调函数更新SDK内token
    //   this.myViewerApiTokenGetter({ viewerApiToken })
    // },
    async myViewerApiTokenGetter(cb) {
      var params = {
        appId: this.playerList.appId, // 账号appId
        channelId: this.playerList.channelId, // 频道号
        timestamp: this.playerList.timestamp, // 时间戳
        viewerId: this.loginList.no, // 观看者用户Id
        sign: this.playerList.sign
      }
      console.log(params, 'params')
      const data = await PolyvApi.getApiToken(params)
      cb({ viewerApiToken: data })
    },

    getLinkParams() {
      // 跳转路径上携带参数如： ***.com?customParams1=自定义参数
      // return {
      //   customParams1: '自定义参数'
      // }
      return {}
    },
    handleBrowseProduct() {
      // TODO 用于统计用户数据
    },
    handleClickBuy() {
      // TODO 用户统计点击商品
    },
    // 点击商品库跳转到商品详情页
    toWatchGoodsDetail() {
      this.$router.push({
        path: '/watch-pack-details',
        query: {
          id: this.$route.query.goods_id,
          isWatch: 1
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.chatroom {
  width: 100%;
  height: 500px;
}

.plv-demo-product {
  position: relative;
  height: 100%;
  background: red;
}
.c-product-bubble {
  position: absolute;
  top: 16px;
  padding-left: 8px;
  z-index: 35;
  width: 100%;
  box-sizing: border-box;
  overflow: hidden;
}
.c-product-bubble--mobile {
  top: 60px;
}
</style>
